package com.ruoyi.system.until;

import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

import com.ruoyi.system.config.QiniuConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class QiniuUploadUtil {

    @Autowired
    private Auth auth;

    @Autowired
    private com.qiniu.storage.Configuration config;

    @Autowired
    private QiniuConfig qiniuConfig;

    public String uploadFile(MultipartFile file) throws IOException {
        UploadManager uploadManager = new UploadManager(config);
        String key = UUID.randomUUID().toString().replace("-", "");
        try {
            byte[] uploadBytes = file.getBytes();
            StringMap putPolicy = new StringMap();
            putPolicy.put("returnBody", "{\"code\":200,\"url\":\"http://" + qiniuConfig.getDomain() + "/$(key)\"}");
            long expireSeconds = 3600;
            String upToken = auth.uploadToken(qiniuConfig.getBucket(), null, expireSeconds, putPolicy);
            Response response = uploadManager.put(uploadBytes, key, upToken);
            if (response.isOK()) {
                return "{\"code\":200,\"url\":\"http://" + qiniuConfig.getDomain() + "/" + key + "\"}";
            } else {
                return "{\"code\":500,\"msg\":\"上传失败\"}";
            }
        } catch (IOException ex) {
            return "{\"code\":500,\"msg\":\"上传失败，发生 IOException\"}";
        }
    }
}
